package com.lianniu.web.util;

import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedList;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtils {
	public static void addCookie(HttpServletRequest request,String id,HttpServletResponse res){
		Cookie cookie = new Cookie("historypro"+request.getParameter("userId"),createValue(request,id));
		cookie.setMaxAge(60*60*24*30);
		cookie.setDomain("localhost"); 
		// 设置path 
		cookie.setPath("/");
		//2.发送cookie
		res.addCookie(cookie);		
	} 
    
    
    
    public static String createValue(HttpServletRequest request,String id){
        Cookie[] cookies = request.getCookies();
        String historypro = null;
        if(cookies!=null){
            for(Cookie c:cookies){
                if(c.getName().equals("historypro"+request.getParameter("userId"))){
                    historypro = c.getValue();
                    break;
                }
            }
        }
        if(cookies==null||historypro==null){
            return id;
        }
        //historypro.contains(id);这种方法不对，原因：id数据类型为String,如果有一个id值为21，同样包含2
        //String -> String[] ->  Collection :为了方便判断重复id
        String[] ids = historypro.split(",");
        Collection colls = Arrays.asList(ids); //<3,21>
        // LinkedList 方便地操作（增删改元素）集合
        // Collection -> LinkedList
        LinkedList list = new LinkedList(colls);
        //不超过3个
        if(list.size()<3){
            //id重复
            if(list.contains(id)){
                //去除重复id，把传入的id放最前面
                list.remove(id);
                list.addFirst(id);
            }else{
                //直接把传入的id放最前面
                list.addFirst(id);
            }
        }else{
            //等于3个
            //id重复
            if(list.contains(id)){
                //去除重复id，把传入的id放最前面
                list.remove(id);
                list.addFirst(id);
            }else{
                //去最后的id，把传入的id放最前面
                list.removeLast();
                list.addFirst(id);
            }
        }
        // LinedList -> String 
        StringBuffer sb = new StringBuffer();
        for (Object object : list) {
            sb.append(object+",");
        }
        //去掉最后的逗号
        String result = sb.toString();
        result = result.substring(0, result.length()-1);
        return result;
    }
}
